#include "comtradedata.h"

/*!
 * \file        comtradedata.cpp
 * \brief       DAT文件内容
 * \details
 * \mainpage
 * \author      Sivan
 * \email
 * \version
 * \date        2022-07-05
 * \license
 */

ComtradeData::ComtradeData(QObject *parent)
    : QObject{parent}
{

}

ComtradeData::~ComtradeData()
{

}

/*!
 * \brief ComtradeData::parse_dat 解析一行数据
 * \param data  内容
 * \param ai_count  模拟量个数
 * \param di_count  开关量个数
 */
void ComtradeData::parse_dat(QByteArray data, int ai_count, int di_count)
{
    QByteArray id = data.mid(0, 4);
    data.remove(0, 4);

    QByteArray time = data.mid(0, 4);
    data.remove(0, 4);

    m_n = fbyte_to_int(id);
    m_timestamp = fbyte_to_int(time);

    //模拟量
    for(int i=0; i<ai_count; i++)
    {
        QByteArray AK = data.mid(0, 2);
        data.remove(0, 2);
        m_AI.append(tbyte_to_int(AK));
    }

    //开关量
    for(int i=0; i<di_count/2; i++)
    {
        QByteArray SM = data.mid(0, 2);
        data.remove(0, 2);
        m_DI.append(tbyte_to_int(SM));
    }
}

/*!
 * \brief ComtradeData::fbyte_to_int    4字节转整形
 * \param bytes
 * \return
 */
int32_t ComtradeData::fbyte_to_int(QByteArray bytes)
{
    QByteArray objId = bytes;
    if(objId.count() != 4) return 0;

//    int32_t objId = bytes[0] & 0x000000FF;
//    objId |= (bytes[1] << 8) & 0x0000FF00;
//    objId |= (bytes[2] << 16) & 0x00FF0000;
//    objId |= (bytes[3] << 24) & 0xFF000000;

    std::reverse(objId.begin(), objId.end());
    return objId.toHex().toInt(nullptr, 16);
}

/*!
 * \brief ComtradeData::tbyte_to_int    2字节转整形
 * \param bytes
 * \return
 */
int16_t ComtradeData::tbyte_to_int(QByteArray bytes)
{
    QByteArray objId = bytes;
    if(objId.count() != 2) return 0;

//    int16_t objId = bytes[0] & 0x000000FF;
//    objId |= (bytes[1] << 8) & 0x0000FF00;

    std::reverse(objId.begin(), objId.end());
    return objId.toHex().toInt(nullptr, 16);
}
